from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
import time
import random
import argparse
import os

class DelayedRequestHandler(SimpleHTTPRequestHandler):
    def __init__(self, *args, delay=0, random_delay=None, **kwargs):
        self.delay = delay
        self.random_delay = random_delay
        super().__init__(*args, **kwargs)

    def end_headers(self):
        self.send_header('Access-Control-Allow-Origin', '*')  # 允许跨域访问
        super().end_headers()

    def do_GET(self):
        # 计算延迟时间
        if self.random_delay:
            delay = random.uniform(self.random_delay[0], self.random_delay[1])
        else:
            delay = self.delay

        time.sleep(delay)  # 添加延迟
        print(f"[请求延迟] {delay:.2f}秒 | 路径: {self.path}")
        super().do_GET()  # 处理原始请求

def main():
    parser = argparse.ArgumentParser(description='带延迟的HTTP文件服务器')
    parser.add_argument('--delay', type=float, default=0, help='固定延迟时间(秒)')
    parser.add_argument('--random-delay', nargs=2, type=float, metavar=('MIN', 'MAX'),
                        help='随机延迟范围(秒)，例如: --random-delay 1 5')
    parser.add_argument('--port', type=int, default=8000, help='服务器端口')
    args = parser.parse_args()

    # 配置延迟参数
    delay_kwargs = {}
    if args.random_delay:
        delay_kwargs = {
            'random_delay': args.random_delay
        }
    else:
        delay_kwargs = {
            'delay': args.delay
        }

    # 启动服务器
    server_address = ('', args.port)
    httpd = ThreadingHTTPServer(
        server_address,
        lambda *args, **kwargs: DelayedRequestHandler(*args, **delay_kwargs, **kwargs)
    )

    # 显示服务器信息
    print(f"服务器运行在 http://localhost:{args.port}")
    if args.random_delay:
        print(f"响应延迟: {args.random_delay[0]}-{args.random_delay[1]}秒随机")
    elif args.delay > 0:
        print(f"响应延迟: 固定{args.delay}秒")
    else:
        print("响应延迟: 未启用")
    print(f"当前目录: {os.getcwd()}")

    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        httpd.shutdown()
        print("\n服务器已停止")

if __name__ == "__main__":
    main()